/*
 * @lc app=leetcode.cn id=129 lang=cpp
 *
 * [129] 求根节点到叶节点数字之和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
    long long ans = 0;

    void dfs(TreeNode *root, long long num)
    {
        num *= 10;
        num += root->val;
        if (root->left)
            dfs(root->left, num);
        if (root->right)
            dfs(root->right, num);
        if (!(root->left) && !(root->right))
        {
            ans += num;
        }
        num /= 10;
    }

    int sumNumbers(TreeNode *root)
    {
        if (!root)
            return 0;
        dfs(root, 0);
        return ans;
    }
};
// @lc code=end
